package com.czkt.sevice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czkt.mapper.SysUserMapper;
import com.czkt.pojo.TSysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lqm
 * @ClassName LoginService
 * @description: TODO
 */
@Service
public class LoginService implements UserDetailsService {
    @Autowired
    SysUserMapper sysUserMapper;


    /**
     * 匹配我们系统的用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("LoginService:loadUserByUsername("+username);


        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");

        //返回规定的User对象
//        User user =new User("admin",new BCryptPasswordEncoder().encode("1234"),auths);

        //从数据库查询
        QueryWrapper<TSysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.lambda().eq(TSysUser::getAccount,username);

        List<TSysUser> list=sysUserMapper.selectList(sysUserQueryWrapper);
        if(list!=null&& !list.isEmpty()){
            User  userDetails = new User(list.get(0).getAccount(), new BCryptPasswordEncoder().encode(list.get(0).getPassword()),auths);
            return userDetails;
        }else{
            return null;
        }
    }
}
